package com.itbupt.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbupt.dto.Result;
import com.itbupt.entity.ShopType;
import com.itbupt.mapper.ShopTypeMapper;
import com.itbupt.service.IShopTypeService;
import com.itbupt.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.itbupt.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * @Author BUPT-Dingchang
 * @Create 2024/5/2 17:13
 * ClassName: ShopTypeServiceImpl
 * Description:
 */

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryList() {

        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        List<String> list = stringRedisTemplate.opsForList().range(key, 0, -1);
        // 存在则返回
        if(CollectionUtil.isNotEmpty(list)){
            //将List<String> 转为 List<ShopType>
            List<ShopType> shopTypes = list.stream()
                    .map(item -> JSONUtil.toBean(item, ShopType.class))
                    .sorted(Comparator.comparingInt(ShopType::getSort))
                    .collect(Collectors.toList());
            return Result.ok(shopTypes);

        }
        // 不存在则查询数据库
        List<ShopType> shopTypes = lambdaQuery().orderByAsc(ShopType::getSort).list();
        // 数据库中不存在，则返回错误信息
        if(CollectionUtil.isEmpty(shopTypes)){
            return Result.fail("商铺类型不存在");
        }
        // 将list<type>转换为List<String>
        List<String> shopTypeCache = shopTypes.stream()
                .sorted(Comparator.comparingInt(ShopType::getSort))
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList());

        // 存在的话，存入redis
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypeCache);
        stringRedisTemplate.expire(key, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return Result.ok(shopTypes);
    }
}
